import { MessageTypeEnum } from "@enum/message-type.enum";
import { showMessage } from "./showMessage";
import { createDialog } from "./createDialog";

export const copyToText = (text: string, messageCallback?: (res: boolean) => void) => {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  document.body.appendChild(textarea);
  textarea.select();
  textarea.setSelectionRange(0, textarea.value.length);
  // 隐藏临时输入框
  textarea.style.setProperty('position', 'fixed');
  textarea.style.setProperty('opacity', '0');
  const res = document.execCommand('copy') && document.queryCommandEnabled('copy');
  document.body.removeChild(textarea);

  if (typeof messageCallback === 'function') {
    messageCallback(res);
  } else {
    if (res) {
      showMessage(MessageTypeEnum.SUCCESS, '复制成功！');
    } else {
      showMessage(MessageTypeEnum.ERROR, '复制失败！请手动复制');
      const body = document.createElement('div');
      const textareaNode = document.createElement('div');
      const texts = text.split('\n');
      
      texts.forEach((item) => {
        const span = document.createElement('span');
        span.textContent = item;
        textareaNode.appendChild(span);
        textareaNode.appendChild(document.createElement('br'));
      });

      textareaNode.style.setProperty('width', '98%');
      textareaNode.style.setProperty('height', '96%');
      textareaNode.style.setProperty('border', '1px solid #d9d9d9');
      textareaNode.style.setProperty('outline', '0px solid transparent');
      textareaNode.style.setProperty('padding', '6px');
      textareaNode.style.setProperty('border-radius', '4px');
      body.appendChild(textareaNode);
      body.style.setProperty('width', '30vw');
      body.style.setProperty('height', '30vh');

      createDialog({
        title: '请手动复制',
        body: body,
        onOk: (closeDialog) => {
          closeDialog();
        }
      });
    }
  }
}
